import time
import configparser
import os
import datetime
from selenium import webdriver
from selenium.webdriver.common.by import By
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.edge.service import Service
from selenium.webdriver.edge.options import Options
from selenium.common.exceptions import TimeoutException, NoSuchElementException

class OutlookAutoLogin:
    """
    Outlook邮箱自动登录类
    使用Selenium WebDriver自动化登录Outlook邮箱
    """
    
    def __init__(self, config_file='config.ini'):
        """
        初始化OutlookAutoLogin类
        
        Args:
            config_file (str): 配置文件路径，默认为'config.ini'
        """
        # 统一配置文件路径（相对于当前脚本所在目录）
        self.config_path = self._resolve_config_path(config_file)

        # 初始化配置解析器
        self.config = configparser.ConfigParser()
        self.driver = None

        # 确保配置存在且有效；必要时引导用户交互创建
        self._ensure_valid_config()

        # 从配置文件读取登录信息
        self.email = self.config.get('outlook', 'email')
        self.password = self.config.get('outlook', 'password')
        self.login_url = self.config.get('outlook', 'login_url')
        
        # 从配置文件读取浏览器设置（如果存在）
        try:
            self.page_load_timeout = self.config.getint('browser', 'page_load_timeout', fallback=30)
            self.element_wait_timeout = self.config.getint('browser', 'element_wait_timeout', fallback=10)
            self.login_wait_timeout = self.config.getint('browser', 'login_wait_timeout', fallback=20)
            self.headless = self.config.getboolean('browser', 'headless', fallback=False)
            self.window_size = self.config.get('browser', 'window_size', fallback='1920,1080')
        except Exception:
            # 如果配置文件中没有browser部分，使用默认值
            self.page_load_timeout = 30
            self.element_wait_timeout = 10
            self.login_wait_timeout = 20
            self.headless = False
            self.window_size = '1920,1080'
        
        # 从配置文件读取调试设置（如果存在）
        try:
            self.debug_enabled = self.config.getboolean('debug', 'enabled', fallback=False)
            self.save_screenshots = self.config.getboolean('debug', 'save_screenshots', fallback=False)
            self.screenshot_path = self.config.get('debug', 'screenshot_path', fallback='screenshots')
        except Exception:
            # 如果配置文件中没有debug部分，使用默认值
            self.debug_enabled = False
            self.save_screenshots = False
            self.screenshot_path = 'screenshots'
        
        # 创建截图目录
        if self.save_screenshots and not os.path.exists(self.screenshot_path):
            os.makedirs(self.screenshot_path)
    
    def setup_driver(self):
        """
        设置Edge WebDriver
        配置浏览器选项和启动参数
        """
        edge_options = Options()
        # 添加一些常用的Edge选项
        edge_options.add_argument('--no-sandbox')
        edge_options.add_argument('--disable-dev-shm-usage')
        edge_options.add_argument('--disable-blink-features=AutomationControlled')
        edge_options.add_experimental_option("excludeSwitches", ["enable-automation"])
        edge_options.add_experimental_option('useAutomationExtension', False)
        
        # 设置用户代理
        edge_options.add_argument('--user-agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36 Edg/120.0.0.0')
        
        # 根据配置设置窗口大小
        if self.window_size:
            edge_options.add_argument(f'--window-size={self.window_size}')
        
        # 根据配置设置无头模式
        # if self.headless:
        #     edge_options.add_argument('--headless')
        
        try:
            # 初始化WebDriver
            self.driver = webdriver.Edge(options=edge_options)
            self.driver.execute_script("Object.defineProperty(navigator, 'webdriver', {get: () => undefined})")
            
            # 设置页面加载超时
            self.driver.set_page_load_timeout(self.page_load_timeout)
            
            print("Edge WebDriver 初始化成功")
        except Exception as e:
            print(f"WebDriver 初始化失败: {e}")
            raise
    
    def login(self):
        """
        执行Outlook邮箱登录流程
        
        Returns:
            bool: 登录是否成功
        """
        try:
            print("开始登录Outlook邮箱...")
            
            # 访问登录页面
            self.driver.get(self.login_url)
            print(f"访问登录页面: {self.login_url}")
            
            # 等待页面加载
            time.sleep(3)
            
            # 输入邮箱地址
            email_input = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.NAME, "loginfmt"))
            )
            email_input.clear()
            email_input.send_keys(self.email)
            print(f"输入邮箱地址: {self.email}")
            
            # 点击下一步按钮
            next_button = self.driver.find_element(By.ID, "idSIButton9")
            next_button.click()
            print("点击下一步按钮")
            
            # 等待密码输入框出现
            time.sleep(3)
            
            # 输入密码
            password_input = WebDriverWait(self.driver, 10).until(
                EC.presence_of_element_located((By.NAME, "passwd"))
            )
            password_input.clear()
            password_input.send_keys(self.password)
            print("输入密码")
            
            # 等待页面响应
            time.sleep(5)
            
            # 点击登录按钮 - 使用多种选择器查找"下一步"或submit按钮
            login_button_selectors = [
                 (By.CSS_SELECTOR, "[data-testid='primaryButton']"),
                 (By.CSS_SELECTOR, "[type='submit']"),
                 (By.XPATH, "//input[contains(@value, '下一步') or contains(@value, 'Next')]")
             ]

            
            login_button = self.find_element_with_multiple_selectors(login_button_selectors)
            if not login_button:
                print("无法找到登录按钮")
                self.take_screenshot("_login_button_not_found")
                return False
                
            login_button.click()
            print("点击登录按钮")
            self.take_screenshot("_after_login_click")
            time.sleep(3)
            
            # 检测并处理浏览器弹窗（如保存密码提示）
            self.handle_browser_popup()
            
            # 等待登录完成
            time.sleep(2)
            
            # 检查是否需要重新输入邮箱（某些情况下会跳转回邮箱输入页面）
            try:
                email_input_check = self.driver.find_element(By.NAME, "loginfmt")
                if email_input_check:
                    print("检测到需要重新输入邮箱")
                    email_input_check.clear()
                    email_input_check.send_keys(self.email)
                    print(f"重新输入邮箱地址: {self.email}")
                    
                    # 查找并点击submit按钮
                    submit_button = self.driver.find_element(By.CSS_SELECTOR, "input[type='submit']")
                    submit_button.click()
                    print("点击提交按钮")
                    time.sleep(3)
            except NoSuchElementException:
                print("未检测到邮箱输入框，继续登录流程")
            except Exception as e:
                print(f"检查邮箱输入框时发生错误: {e}")
            
            # 检查是否需要处理"保持登录"选项
            try:
                stay_signed_in = WebDriverWait(self.driver, 5).until(
                    EC.presence_of_element_located((By.ID, "idSIButton9"))
                )
                if "保持登录" in self.driver.page_source or "Stay signed in" in self.driver.page_source:
                    print("处理保持登录选项")
                    stay_signed_in.click()
                    time.sleep(3)
            except TimeoutException:
                print("未发现保持登录选项，继续...")
            
            # 等待跳转到Outlook主页面
            WebDriverWait(self.driver, 20).until(
                lambda driver: "outlook.office.com" in driver.current_url or "outlook.live.com" in driver.current_url
            )
            
            print("登录成功！")
            print(f"当前页面URL: {self.driver.current_url}")
            return True
            
        except TimeoutException as e:
            print(f"登录超时: {e}")
            return False
        except NoSuchElementException as e:
            print(f"页面元素未找到: {e}")
            return False
        except Exception as e:
            print(f"登录过程中发生错误: {e}")
            return False
    
    def wait_and_interact(self, wait_time=30):
        """
        等待用户交互或指定时间
        
        Args:
            wait_time (int): 等待时间（秒），默认30秒
        """
        print(f"浏览器将保持打开状态 {wait_time} 秒，您可以进行其他操作...")
        time.sleep(wait_time)
    
    def close(self):
        """
        关闭浏览器
        """
        if self.driver:
            self.driver.quit()
            print("浏览器已关闭")
    
    def run(self):
        """
        运行完整的登录流程
        """
        try:
            # 设置WebDriver
            self.setup_driver()
            
            # 执行登录
            if self.login():
                print("\n=== 登录成功 ===")
                print("您现在可以使用Outlook邮箱了")
                
                # 发送测试邮件
                print("\n=== 发送测试邮件 ===")
                if self.send_test_email(recipient_email="2504880498@qq.com"):
                    print("测试邮件发送成功！")
                else:
                    print("测试邮件发送失败，但登录功能正常")
                
                # 等待用户交互
                self.wait_and_interact(60)  # 等待60秒
            else:
                print("\n=== 登录失败 ===")
                print("请检查配置文件中的邮箱地址和密码是否正确")
                
        except Exception as e:
            print(f"程序运行出错: {e}")
        # finally:
        #     # 关闭浏览器
        #     self.close()
    
    def find_element_with_multiple_selectors(self, selectors, timeout=None):
        """
        使用多个选择器尝试查找元素
        
        Args:
            selectors (list): 选择器列表，每个元素为(By, selector)元组
            timeout (int): 超时时间，默认使用配置文件中的element_wait_timeout
        
        Returns:
            WebElement: 找到的元素，如果都找不到则返回None
        """
        if timeout is None:
            timeout = self.element_wait_timeout
        
        for by, selector in selectors:
            try:
                self.debug_print(f"尝试查找元素: {by} = {selector}")
                element = WebDriverWait(self.driver, timeout).until(
                    EC.element_to_be_clickable((by, selector))
                )
                self.debug_print(f"成功找到元素: {by} = {selector}")
                return element
            except TimeoutException:
                self.debug_print(f"未找到元素: {by} = {selector}")
                continue
        
        return None
    
    def take_screenshot(self, suffix=""):
        """
        保存截图
        
        Args:
            suffix (str): 文件名后缀
        """
        if self.save_screenshots and self.driver:
            try:
                timestamp = time.strftime("%Y%m%d_%H%M%S")
                filename = f"screenshot_{timestamp}{suffix}.png"
                filepath = os.path.join(self.screenshot_path, filename)
                self.driver.save_screenshot(filepath)
                self.debug_print(f"截图已保存: {filepath}")
            except Exception as e:
                print(f"保存截图失败: {e}")
    
    def debug_print(self, message):
        """
        打印调试信息
        
        Args:
            message (str): 要打印的调试信息
        """
        if self.debug_enabled:
            print(f"[DEBUG] {message}")

    def _resolve_config_path(self, config_file: str) -> str:
        """
        解析并返回配置文件的绝对路径
        
        Args:
            config_file (str): 传入的配置文件路径（可相对或绝对）
        
        Returns:
            str: 配置文件的绝对路径
        """
        base_dir = os.path.dirname(os.path.abspath(__file__))
        if os.path.isabs(config_file):
            return config_file
        return os.path.join(base_dir, config_file)

    def _is_outlook_section_valid(self) -> bool:
        """
        校验配置中是否存在有效的[outlook]段及必要键
        
        Returns:
            bool: 若存在有效的邮箱、密码与登录URL则返回True
        """
        if not self.config.has_section('outlook'):
            return False
        required_keys = ['email', 'password', 'login_url']
        for key in required_keys:
            if not self.config.has_option('outlook', key):
                return False
            val = self.config.get('outlook', key)
            if val is None or str(val).strip() == '':
                return False
        return True

    def _write_default_config(self, email: str, password: str, login_url: str) -> None:
        """
        将用户提供的信息写入config.ini，并补充可选段落
        
        Args:
            email (str): 邮箱地址
            password (str): 邮箱密码
            login_url (str): 登录页面URL
        """
        cfg = configparser.ConfigParser()
        cfg['outlook'] = {
            'email': email,
            'password': password,
            'login_url': login_url,
        }
        cfg['browser'] = {
            'page_load_timeout': '30',
            'element_wait_timeout': '10',
            'login_wait_timeout': '20',
            'headless': 'False',
            'window_size': '1920,1080',
        }
        cfg['debug'] = {
            'enabled': 'False',
            'save_screenshots': 'False',
            'screenshot_path': 'screenshots',
        }
        with open(self.config_path, 'w', encoding='utf-8') as f:
            cfg.write(f)

    def _ensure_valid_config(self) -> None:
        """
        确保配置文件存在且包含有效的登录信息；否则引导交互创建。
        """
        # 若存在文件则尝试读取
        if os.path.exists(self.config_path):
            try:
                self.config.read(self.config_path, encoding='utf-8')
            except Exception as e:
                print(f"读取配置文件失败: {e}")
        
        # 校验[outlook]段是否合法
        if self._is_outlook_section_valid():
            return

        print("未检测到有效的配置，准备创建配置文件：")
        print(f"配置路径: {self.config_path}")

        # 交互收集必要信息
        try:
            default_login_url = (
                "https://login.microsoftonline.com/common/oauth2/v2.0/authorize?client_id=9199bf20-a13f-4107-85dc-02114787ef48&scope=https%3A%2F%2Foutlook.office.com%2F.default%20openid%20profile%20offline_access&redirect_uri=https%3A%2F%2Foutlook.office.com%2Fmail%2F&response_type=code"
            )
            email = input("请输入Outlook邮箱地址: ").strip()
            password = input("请输入邮箱密码(将以明文写入本地配置): ").strip()
            login_url = input(f"请输入登录URL(回车使用默认): \n默认: {default_login_url}\n> ").strip() or default_login_url

            if not email or not password:
                raise ValueError("邮箱与密码不能为空")

            # 写入配置并重新读取
            self._write_default_config(email, password, login_url)
            self.config.read(self.config_path, encoding='utf-8')
            print("配置已生成并保存，继续运行...")
        except Exception as e:
            print(f"创建配置失败: {e}")
            raise
    
    def handle_browser_popup(self):
        """
        检测并处理浏览器弹窗（如保存密码提示）
        
        Returns:
            bool: 是否检测到并处理了弹窗
        """
        try:
            self.debug_print("开始检测浏览器弹窗...")
            
            # 常见的弹窗关闭按钮选择器
            popup_close_selectors = [
                # 保存密码弹窗的关闭按钮
                (By.CSS_SELECTOR, "button[aria-label='关闭']"),
                (By.CSS_SELECTOR, "button[aria-label='Close']"),
                (By.CSS_SELECTOR, "button[title='关闭']"),
                (By.CSS_SELECTOR, "button[title='Close']"),
                (By.CSS_SELECTOR, "button.ms-Button--icon[aria-label*='关闭']"),
                (By.CSS_SELECTOR, "button.ms-Button--icon[aria-label*='Close']"),
                # 通用关闭按钮
                (By.CSS_SELECTOR, "button[data-testid='close-button']"),
                (By.CSS_SELECTOR, "button[class*='close']"),
                (By.CSS_SELECTOR, "div[role='button'][aria-label*='关闭']"),
                (By.CSS_SELECTOR, "div[role='button'][aria-label*='Close']"),
                # X 按钮
                (By.XPATH, "//button[contains(text(), '×') or contains(text(), 'X')]"),
                (By.CSS_SELECTOR, "button[aria-label='×']"),
                # 保存密码弹窗的"以后再说"或"不保存"按钮
                (By.XPATH, "//button[contains(text(), '以后再说') or contains(text(), 'Not now') or contains(text(), '不保存') or contains(text(), 'Never')]"),
                # 通知弹窗的关闭按钮
                (By.CSS_SELECTOR, "button[data-testid='notification-close']"),
                (By.CSS_SELECTOR, "div[class*='notification'] button[class*='close']"),
            ]
            
            # 尝试查找并点击关闭按钮
            for selector_type, selector_value in popup_close_selectors:
                try:
                    elements = self.driver.find_elements(selector_type, selector_value)
                    if elements:
                        for element in elements:
                            # 检查元素是否可见和可点击
                            if element.is_displayed() and element.is_enabled():
                                element.click()
                                self.debug_print(f"已关闭弹窗，使用选择器: {selector_value}")
                                self.take_screenshot("popup_closed")
                                time.sleep(1)
                                return True
                except Exception as e:
                    # 忽略单个选择器的错误，继续尝试下一个
                    continue
            
            # 检查是否有模态对话框需要处理
            try:
                # 查找模态对话框
                modal_selectors = [
                    (By.CSS_SELECTOR, "div[role='dialog']"),
                    (By.CSS_SELECTOR, "div[class*='modal']"),
                    (By.CSS_SELECTOR, "div[class*='popup']"),
                    (By.CSS_SELECTOR, "div[data-testid*='dialog']"),
                ]
                
                for selector_type, selector_value in modal_selectors:
                    modals = self.driver.find_elements(selector_type, selector_value)
                    if modals:
                        for modal in modals:
                            if modal.is_displayed():
                                # 在模态框内查找关闭按钮
                                close_buttons = modal.find_elements(By.CSS_SELECTOR, "button[aria-label*='关闭'], button[aria-label*='Close'], button[title*='关闭'], button[title*='Close']")
                                if close_buttons:
                                    for btn in close_buttons:
                                        if btn.is_displayed() and btn.is_enabled():
                                            btn.click()
                                            self.debug_print("已关闭模态对话框")
                                            self.take_screenshot("modal_closed")
                                            time.sleep(1)
                                            return True
            except Exception as e:
                self.debug_print(f"处理模态对话框时出错: {str(e)}")
            
            # 尝试按ESC键关闭弹窗
            try:
                from selenium.webdriver.common.keys import Keys
                self.driver.find_element(By.TAG_NAME, "body").send_keys(Keys.ESCAPE)
                self.debug_print("已尝试使用ESC键关闭弹窗")
                time.sleep(1)
            except Exception as e:
                self.debug_print(f"使用ESC键关闭弹窗失败: {str(e)}")
            
            self.debug_print("未检测到需要处理的弹窗")
            return False
            
        except Exception as e:
            self.debug_print(f"处理浏览器弹窗时出错: {str(e)}")
            self.take_screenshot("popup_handle_error")
            return False
    
    def send_test_email(self, recipient_email=None):
        """
        发送测试邮件
        
        Args:
            recipient_email (str): 收件人邮箱地址，如果为None则发送给自己
        
        Returns:
            bool: 发送是否成功
        """
        try:
            print("开始发送测试邮件...")
            
            # 如果没有指定收件人，则发送给自己
            if recipient_email is None:
                recipient_email = self.email
            
            # 等待页面完全加载
            time.sleep(3)
            
            # 查找并点击"新邮件"按钮
            compose_selectors = [
                # 最精确的选择器 - 基于用户提供的HTML结构
                (By.CSS_SELECTOR, "button[data-automation-type='RibbonSplitButton'][aria-label='新邮件']"),
                (By.CSS_SELECTOR, "button[data-unique-id='Ribbon-588'][aria-label='新邮件']"),
                (By.CSS_SELECTOR, "button.splitPrimaryButton[aria-label='新邮件']"),
                (By.CSS_SELECTOR, "button[data-automation-type='RibbonSplitButton'][class*='splitPrimaryButton']"),
                # 原有的精确选择器
                (By.CSS_SELECTOR, "[aria-label='新邮件']"),
                (By.CSS_SELECTOR, "button[aria-label='新邮件']"),
                (By.CSS_SELECTOR, "div[aria-label='新邮件']"),
                # 基于图标的选择器
                (By.CSS_SELECTOR, "button i[data-icon-name='ComposeRegular']"),
                (By.CSS_SELECTOR, "button span:contains('新邮件')")
            ]
            
            compose_button = self.find_element_with_multiple_selectors(compose_selectors, timeout=10)
            if not compose_button:
                print("无法找到新建邮件按钮")
                self.take_screenshot("_compose_button_not_found")
                return False
            
            compose_button.click()
            print("点击新建邮件按钮")
            self.take_screenshot("_after_compose_click")
            
            # 等待邮件编辑窗口出现
            time.sleep(3)
            
            # 点击抄送按钮
            cc_button_selectors = [
                (By.XPATH, "//button[@type='button' and text()='抄送']"),
                (By.XPATH, "//button[@type='button' and contains(text(), '抄送')]"),
                (By.CSS_SELECTOR, "button[type='button']:contains('抄送')"),
                # 基于用户提供的HTML结构的精确选择器
                (By.CSS_SELECTOR, "button.fui-Button:contains('抄送')"),
                (By.CSS_SELECTOR, "button[class*='fui-Button']:contains('抄送')"),
                (By.XPATH, "//button[contains(@class, 'fui-Button') and text()='抄送']"),
                # 组合选择器 - type + class + text
                (By.XPATH, "//button[@type='button' and contains(@class, 'fui-Button') and text()='抄送']"),
                # 简化的精确选择器
                (By.CSS_SELECTOR, "button[aria-label='抄送']"),
                (By.CSS_SELECTOR, "[aria-label='抄送']"),

            ]
            
            cc_button = self.find_element_with_multiple_selectors(cc_button_selectors, timeout=10)
            if cc_button:
                cc_button.click()
                self.debug_print("已点击抄送按钮")
                self.take_screenshot("cc_button_clicked")
                time.sleep(2)
                 
                 # 输入抄送邮箱
                cc_input_selectors = [
                    (By.CSS_SELECTOR, "[aria-label='抄送']"),
                    (By.CSS_SELECTOR, "input[aria-label='抄送']"),
                    (By.CSS_SELECTOR, "div[aria-label='抄送']"),
                    (By.CSS_SELECTOR, "input[aria-label*='抄送']"),
                    (By.CSS_SELECTOR, "input[aria-label*='CC']"),
                    (By.CSS_SELECTOR, "input[placeholder*='抄送']"),
                    (By.CSS_SELECTOR, "input[placeholder*='CC']"),
                    (By.CSS_SELECTOR, "div[contenteditable='true'][aria-label*='抄送']"),
                    (By.CSS_SELECTOR, "div[contenteditable='true'][aria-label*='CC']"),
                    (By.CSS_SELECTOR, "div[role='textbox'][aria-label*='抄送']"),
                    (By.CSS_SELECTOR, "div[role='textbox'][aria-label*='CC']")
                ]
                 
                cc_input = self.find_element_with_multiple_selectors(cc_input_selectors, timeout=10)
                if cc_input:
                    cc_input.clear()
                    cc_input.send_keys("2117973676@qq.com")
                    self.debug_print("已输入抄送邮箱: 2117973676@qq.com")
                    self.take_screenshot("cc_email_entered")
                    time.sleep(1)
                else:
                    self.debug_print("未找到抄送输入框")
                    self.take_screenshot("cc_input_not_found")
            else:
                self.debug_print("未找到抄送按钮")
                self.take_screenshot("cc_button_not_found")
            
            # 输入收件人
            to_selectors = [
                (By.CSS_SELECTOR, "[aria-label='收件人']"),
                (By.CSS_SELECTOR, "input[aria-label='收件人']"),
                (By.CSS_SELECTOR, "div[aria-label='收件人']"),
                (By.CSS_SELECTOR, "input[aria-label*='收件人']"),
                (By.CSS_SELECTOR, "input[aria-label*='To']"),
                (By.CSS_SELECTOR, "input[placeholder*='收件人']"),
                (By.CSS_SELECTOR, "input[placeholder*='To']"),
                (By.CSS_SELECTOR, "div[aria-label*='收件人'] input"),
                (By.CSS_SELECTOR, "div[aria-label*='To'] input"),
                (By.XPATH, "//input[contains(@aria-label, '收件人') or contains(@aria-label, 'To')]"),
                (By.CSS_SELECTOR, "input[data-testid*='to']"),
                (By.CSS_SELECTOR, "input[name*='to']"),
                (By.CSS_SELECTOR, "div[contenteditable='true'][aria-label*='收件人']"),
                (By.CSS_SELECTOR, "div[contenteditable='true'][aria-label*='To']")
            ]
            
            to_field = self.find_element_with_multiple_selectors(to_selectors, timeout=10)
            if not to_field:
                print("无法找到收件人输入框")
                self.take_screenshot("_to_field_not_found")
                return False
            
            to_field.clear()
            to_field.send_keys(recipient_email)
            print(f"输入收件人: {recipient_email}")
            
            # 等待输入完成
            time.sleep(2)
            
            # 输入主题
            subject_selectors = [
                (By.CSS_SELECTOR, "[aria-label='主题']"),
                (By.CSS_SELECTOR, "input[aria-label='主题']"),
                (By.CSS_SELECTOR, "div[aria-label='主题']"),
                (By.CSS_SELECTOR, "input[aria-label*='主题']"),
                (By.CSS_SELECTOR, "input[aria-label*='Subject']"),
                (By.CSS_SELECTOR, "input[placeholder*='主题']"),
                (By.CSS_SELECTOR, "input[placeholder*='Subject']"),
                (By.CSS_SELECTOR, "input[data-testid*='subject']"),
                (By.CSS_SELECTOR, "input[name*='subject']"),
                (By.XPATH, "//input[contains(@aria-label, '主题') or contains(@aria-label, 'Subject')]"),
                (By.CSS_SELECTOR, "div[contenteditable='true'][aria-label*='主题']"),
                (By.CSS_SELECTOR, "div[contenteditable='true'][aria-label*='Subject']")
            ]
            
            subject_field = self.find_element_with_multiple_selectors(subject_selectors, timeout=10)
            if not subject_field:
                print("无法找到主题输入框")
                self.take_screenshot("_subject_field_not_found")
                return False
            
            test_subject = "Outlook自动登录cs邮件"
            subject_field.clear()
            subject_field.send_keys(test_subject)
            print(f"输入主题: {test_subject}")
            
            # 等待输入完成
            time.sleep(2)
            
            # 输入邮件内容
            body_selectors = [
                (By.CSS_SELECTOR, "[aria-label='邮件正文，按 Alt+F10 退出']"),
                (By.CSS_SELECTOR, "div[aria-label='邮件正文，按 Alt+F10 退出']"),
                (By.CSS_SELECTOR, "textarea[aria-label='邮件正文，按 Alt+F10 退出']"),
                (By.CSS_SELECTOR, "div[aria-label*='邮件正文']"),
                (By.CSS_SELECTOR, "div[aria-label*='Message body']"),
                (By.CSS_SELECTOR, "div[contenteditable='true'][role='textbox']"),
                (By.CSS_SELECTOR, "div[data-testid*='body']"),
                (By.CSS_SELECTOR, "div[data-testid*='editor']"),
                (By.CSS_SELECTOR, "iframe[title*='Rich Text Editor']"),
                (By.XPATH, "//div[contains(@aria-label, '邮件正文') or contains(@aria-label, 'Message body')]"),
                (By.CSS_SELECTOR, "div.ms-editor-content"),
                (By.CSS_SELECTOR, "div[role='textbox'][contenteditable='true']")
            ]
            
            body_field = self.find_element_with_multiple_selectors(body_selectors, timeout=10)
            if not body_field:
                print("无法找到邮件正文输入框")
                self.take_screenshot("_body_field_not_found")
                return False
            
            current_time = datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")
            test_content = f"""这是一封自动发送的cs邮件。
            发送者: taxi
            如果您收到这封邮件，说明你在上班摸鱼，报警。
            此邮件由程序自动生成，请勿回复。"""
            
            body_field.clear()
            body_field.send_keys(test_content)
            print("输入邮件内容")
            
            # 等待输入完成
            time.sleep(3)
            
            # 查找并点击发送按钮
            send_selectors = [
                (By.CSS_SELECTOR, "button[aria-label*='发送']"),
                (By.CSS_SELECTOR, "button[aria-label*='Send']"),
                (By.CSS_SELECTOR, "button[data-testid*='send']"),
                (By.CSS_SELECTOR, "button[title*='发送']"),
                (By.CSS_SELECTOR, "button[title*='Send']"),
                (By.XPATH, "//button[contains(text(), '发送') or contains(text(), 'Send')]"),
                (By.CSS_SELECTOR, "div[role='button'][aria-label*='发送']"),
                (By.CSS_SELECTOR, "div[role='button'][aria-label*='Send']"),
                (By.CSS_SELECTOR, "button[name*='send']"),
                (By.CSS_SELECTOR, "input[type='submit'][value*='发送']"),
                (By.CSS_SELECTOR, "input[type='submit'][value*='Send']")
            ]
            
            send_button = self.find_element_with_multiple_selectors(send_selectors, timeout=10)
            if not send_button:
                print("无法找到发送按钮")
                self.take_screenshot("_send_button_not_found")
                return False
            
            send_button.click()
            print("点击发送按钮")
            self.take_screenshot("_after_send_click")
            
            # 等待发送完成
            time.sleep(5)
            
            print("测试邮件发送成功！")
            return True
            
        except Exception as e:
            print(f"发送测试邮件时发生错误: {e}")
            self.take_screenshot("_send_email_error")
            return False

def main():
    """
    主函数
    创建OutlookAutoLogin实例并运行登录流程
    """
    print("=== Outlook 邮箱自动登录工具 ===")
    print("正在启动...")
    
    # 创建登录实例
    outlook_login = OutlookAutoLogin()
    
    # 运行登录流程
    outlook_login.run()

if __name__ == "__main__":
    main()